<template>
  <div v-if="value" class="avatar-box">
    <CloseCircleFilled @click.stop="del()" class="del" :style="{fontSize: '18px', color: '#999', zIndex: 1000}" />
    <a-image :src="value" alt="avatar" class="img" />
  </div>
  <a-upload
    v-else
    name="file"
    list-type="picture-card"
    class="avatar-uploader"
    :show-upload-list="false"
    :action="uploadUrl"
    @change="handleChange"
  >
    <loading-outlined v-if="loading" />
    <plus-outlined v-else></plus-outlined>
    <div class="ant-upload-text">{{text}}</div>
  </a-upload>
</template>
<script lang="ts">
import { message } from 'ant-design-vue';
import type { UploadChangeParam } from 'ant-design-vue';

export default {
	name: "AvatarUploader",
	props: {
		value: {
			type: String,
			default: ''
		},
		label:  {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			// imageRoot: import.meta.env.VITE_APP_BASE_API + '/',
			text: '上传',
			loading: false as boolean,
			form: {
				name: ''
			},
			uploadUrl: import.meta.env.VITE_APP_BASE_API + '/file/upload'
		};
	},
	mounted() {
		this.text = this.label
	},
	methods: {
		handleChange (info: UploadChangeParam) {
			if (info.file.status === 'uploading') {
				this.loading = true;
				return;
			}
			if (info.file.status === 'done') {
				if(info.file.response.code == 200){
					this.$emit('update:value', info.file.response.data)
					this.loading = false;
				} else {
					message.error(info.file.response.message);
				}
			}
			if (info.file.status === 'error') {
				this.loading = false;
				message.error('upload error');
			}
		},
		del(){
			this.$emit('update:value', '')
		}
	}
}
</script>
<style scoped>
.avatar-uploader > .ant-upload, .avatar-box {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.avatar-box{position: relative; }
.del{position: absolute; top: -8px; right: -8px; }
.img{width: 100%; height: 100%;}
</style>